package com.jiahao.material.configs;


import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.jiahao.material.utils.DateUtil;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Random;

@Component
public class MyMetaObjectHandle implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {

        this.setFieldValByName("createTime", new Date(),metaObject);

        this.setFieldValByName("wcode",getCode("W"),metaObject);

        this.setFieldValByName("dcode",getCode("D"),metaObject);

    }

    @Override
    public void updateFill(MetaObject metaObject) {

        this.setFieldValByName("updateTime",new Date(),metaObject);
    }

    private String getCode(String first){
        StringBuilder stringBuilder = new StringBuilder(first);

        //时间戳
        String datetime = DateUtil.dateToStr(new Date(),DateUtil.FORMAT_DATE_TIME);

        //000-999随机数
        Random random = new Random();
        StringBuilder random_code = new StringBuilder(Integer.toString(random.nextInt(999)));
        while (random_code.length()<3){
            random_code.insert(0,"0");
        }

        //结合
        return stringBuilder.append(datetime).append(random_code).toString();

    }
}
